<template>
	<div class="my-goods-list">
		<MyTable :arr="list">
			<template #head>
				<th>#</th>
				<th>商品名称</th>
				<th>价格</th>
				<th>标签</th>
				<th>操作</th> 
			</template>
			<!-- 插槽内使用组件数据 -->
			<template #body="scoped">
				<td>{{scoped.obj.id}}</td>
				<td>{{scoped.obj.goods_name}}</td>
				<td>{{scoped.obj.goods_price}}</td>
				<td>
					<div>
						<!-- input和button是互斥效果 v-if 和v-else -->
						<!-- 输入框 -->
						<input style="width: 150px" class="tag-input form-control" type="text" v-if="scoped.obj.inputVisible"
						v-model.trim="scoped.obj.inputValue"
						v-focus
						@blur="scoped.obj.inputVisible = false"
						@keyup.esc="scoped.obj.inputValue = ''"
						@keyup.enter="addFn(scoped.obj)"
						/>
						<!-- 输入框敲回车，把inputValue 添加到tags数组中 -->
						<!-- 指令内的简单代码 -->
						<button @click="scoped.obj.inputVisible = true" v-else class="btn btn-primary btn-sm add-tag">
							+Tag
						</button>
					</div>
					<!-- 遍历 -->
					<span class="badge bg-warning text-dark" v-for="(item,index) in scoped.obj.tags" :key="index">{{item}}</span>
				</td>
				<td><button class="btn btn-danger btn-sm" @click="delFn(scoped.obj.id)">删除</button></td>
			</template>
		</MyTable>
	</div>
</template>

<script>
//todo 父传子 把list数组传输给子组件。v-for渲染
import axios from 'axios';
import MyTable from '../components/MyTable.vue'
	// 接口：GTE  https://www.escook.cn/api/goods

	export default {
		data() {
			return {
				list:[]
			};
		},
		async created () {
			const {data:res} = await axios.get('https://www.escook.cn/api/goods')
			this.list = res.data
		},
		components:{
			MyTable,
		},
		methods:{
			delFn(id){
				console.log(id)
			return this.list =	this.list.filter(item => item.id !== id)
			},
			addFn(obj){
				//判断
				if(obj.inputValue === ''){
					return alert('输入内容')
				}
				//添加
				obj.tags.push(obj.inputValue)
				obj.inputValue = ''
			}
		},
		//自定义指令
		directives:{
			focus:{
				inserted(el){
					el.focus()
				}
			}
		}
	};
</script>

<style>
</style>
